import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Card, Spin, message, Icon} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, PAGE, FILES_API} from '../constants';
import {conventEnumValueToString} from '../utils';
import {PERMISSION} from './constants';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import Return from '../common/Return';
import {validateAdd} from './utils';
import OrderSelectPanel from './OrderSelectPanel';
import ForwarderSelectPanel from './ForwarderSelectPanel';
import {partOrderPriceTerms} from '../Enum';
import InputAmount from '../common/InputAmount';
const FormItem = Form.Item;
const autosize = {minRows: 1};
const EMPTY_ARRAY = [];
const basePath = fetch.basePath || '';
export const fileApi = `${basePath}${FILES_API.files}`;
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        isForwarderSearch: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    onClickIcon = () => {
        this.setState({
            isForwarderSearch: !this.state.isForwarderSearch
        });
    }
   
    onSelectOrder = record => {
        this.setState({
            hasOperat: true,
        });
        if(record && record.id !== this.props.conditions.partShipmentId)
            this.props.onSelectOrder(record);
    };

    onSelectForwarder = record => {
        this.setState({
            hasOperat: true,
        });
        if(record && record.contactId !== this.props.conditions.forwarderId)
            this.props.onSelectForwarder(record);
    };

    onSubmit = () => {
        const result = validateAdd(this.props.conditions, this.props.id);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    render() {
        const forwarderLabel = (<span>
            {this.props.intl.formatMessage({
                id: 'add.form.forwarder',
                defaultMessage: '货代名称'
            })}
            {'  '}
            {this.state.isForwarderSearch ? (<Icon type="undo" className={`${styles.cursor} ${styles.blue}`} title={this.props.intl.formatMessage({
                id: 'add.form.icon.reset',
                defaultMessage: '还原'
            })} onClick={this.onClickIcon} />)
                : (<Icon type="edit" theme="twoTone" className={styles.cursor}
                    title={this.props.intl.formatMessage({
                        id: 'add.form.icon.edit',
                        defaultMessage: '下拉选择'
                    })}
                    onClick={this.onClickIcon} />)}
        </span>);
        const forwarderInfo = this.props.conditions.forwarderId && this.state.isForwarderSearch ? {
            contactId: this.props.conditions.forwarderId,
            name: this.props.conditions.forwarder,
        } : null;
        const orderInfo = this.props.conditions.partShipmentId ? {
            id: this.props.conditions.partShipmentId,
            partContractInvoiceCode: this.props.conditions.partContractInvoiceCode,
        } : null;
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.card.title',
                                defaultMessage: '委托书信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.partContractInvoiceCode ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.partContractInvoiceCode',
                                            defaultMessage: '备件箱单发票'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.id ? this.props.conditions.partContractInvoiceCode
                                            : <OrderSelectPanel
                                                value={orderInfo}
                                                onSelect={this.onSelectOrder} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.exporter ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.exporter',
                                            defaultMessage: '卖方'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="exporter"
                                            value={this.props.conditions.exporter} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.importer ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.importer',
                                            defaultMessage: '买方名称'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="importer"
                                            value={this.props.conditions.importer} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.loadingPort ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.loadingPort',
                                            defaultMessage: '起运地'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="loadingPort"
                                            value={this.props.conditions.loadingPort} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.destinationPort ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.destinationPort',
                                            defaultMessage: '目的地'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="destinationPort"
                                            value={this.props.conditions.destinationPort} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.priceTerms',
                                            defaultMessage: '价格条款'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{conventEnumValueToString(partOrderPriceTerms, this.props.conditions.priceTerms)}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.shippingFee',
                                            defaultMessage: '运费价格'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <InputAmount
                                            name="shippingFee"
                                            value={this.props.conditions.shippingFee}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.carrier',
                                            defaultMessage: '载体'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="carrier"
                                            value={this.props.conditions.carrier} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.importerCantact',
                                            defaultMessage: '买方联系人'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="importerCantact"
                                            value={this.props.conditions.importerCantact} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.importerNumber',
                                            defaultMessage: '买方电话'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="importerNumber"
                                            value={this.props.conditions.importerNumber} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.contactEmail',
                                            defaultMessage: '联系人电子邮件'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="contactEmail"
                                            value={this.props.conditions.contactEmail} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.contactFax',
                                            defaultMessage: '联系人传真'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="contactFax"
                                            value={this.props.conditions.contactFax} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.notifyParty',
                                            defaultMessage: '通知方'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="notifyParty"
                                            value={this.props.conditions.notifyParty} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={forwarderLabel}
                                        {...FORM_OPTIONS.item}>
                                        {
                                            this.state.isForwarderSearch ? <ForwarderSelectPanel
                                                value={forwarderInfo}
                                                brandId={this.props.conditions.brandId}
                                                onSelect={this.onSelectForwarder} /> : <TextInput name="forwarder"
                                                value={this.props.conditions.forwarder} onBlur={this.handleFilterChange} />
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.forwarderContact',
                                            defaultMessage: '货代联系人'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="forwarderContact"
                                            value={this.props.conditions.forwarderContact} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.forwarderNumber',
                                            defaultMessage: '货代电话'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="forwarderNumber"
                                            value={this.props.conditions.forwarderNumber} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.forwarderFax',
                                            defaultMessage: '货代传真'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="forwarderFax"
                                            value={this.props.conditions.forwarderFax} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.dischargePort',
                                            defaultMessage: '卸货港'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput name="dischargePort"
                                            value={this.props.conditions.dischargePort} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.remark',
                                        defaultMessage: '备注'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput type="textarea" name="remark" autosize={autosize}
                                        value={this.props.conditions.remark} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        <Card title={this.props.intl.formatMessage({
                            id: 'add.gatherInfo.title',
                            defaultMessage: '委托书汇总'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.packingListTotal',
                                            defaultMessage: '箱数'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.packingListTotal}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.grossWeightTotal',
                                            defaultMessage: '毛重'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.grossWeightTotal}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.volumeTotal',
                                            defaultMessage: '体积'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.volumeTotal}</span>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.shippingMark',
                                            defaultMessage: '唛头'
                                        })}
                                        {...FORM_ROW_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.shippingMark}</span>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.description',
                                            defaultMessage: '货物描述'
                                        })}
                                        {...FORM_ROW_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.description}</span>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        {this.props.conditions.companySeal ? <Card
                            hoverable
                            className={styles.cardImg}
                            title="Company Seal"
                            cover={<img src={`${fileApi}/${this.props.conditions.companySeal}`} />}>
                        </Card> : null}
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            type="primary"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}>
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.save',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onSelectForwarder: PropTypes.func.isRequired,
    onSelectOrder: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    selectForwarder,
    onClickUpdate,
    selectOrder,
    getDetail,
} from './actions';
import {createSelector} from 'reselect';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';

const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.id,
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, id, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        const submitable = id ? data.includes(PERMISSION.update) && options.includes(PERMISSION.update)
            : data.includes(PERMISSION.add);
        return submitable;
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => {
        if(ownProps.id)
            return dispatch(getDetail(ownProps.id));
        return null;
    },
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: status =>
        dispatch(onClickUpdate(ownProps.id, status)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onSelectOrder: data => dispatch(selectOrder(data)),
    onSelectForwarder: data => dispatch(selectForwarder(data)),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
